package com.maxd.controller;

import com.google.common.collect.Lists;
import com.maxd.adapter.IgnoreSecurity;
import com.maxd.adapter.LoginUserHolder;
import com.maxd.bean.PageRes;
import com.maxd.bean.requirement.UpdateRequireStatusReq;
import com.maxd.error.ExceptionEnum;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.InstructorInfo;
import com.maxd.model.RequirementInfo;
import com.maxd.respository.RequirementInfoRepository;
import com.maxd.utils.AdminUtils;
import com.maxd.utils.AssertUtil;
import com.maxd.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.util.Date;
import java.util.List;

@RestController
@Api(value="社区公益需求管理", tags = {"社区公益需求管理"})
@RequestMapping(value = "/requirement")
public class RequirementController {

    @Autowired
    private RequirementInfoRepository requirementInfoRepository;

    @ApiOperation("新增/修改需求信息")
    @PostMapping("/save")
    public Result<Void> save(@RequestBody @Validated RequirementInfo requirementInfo) {
        Long userId = LoginUserHolder.getUserId();
        AssertUtil.assertTrue(userId != null && userId > 0, ExceptionEnum.WRONT_TOKEN);

        requirementInfo.setUserId(userId);
        if(requirementInfo.getId() != null) {
            requirementInfo.setUpdateTime(new Date());
            requirementInfo.setUpdateBy(String.valueOf(LoginUserHolder.getUserId()));
        } else {
            requirementInfo.setStatus("0");
            requirementInfo.setCreateBy(String.valueOf(LoginUserHolder.getUserId()));
            requirementInfo.setUpdateBy(String.valueOf(LoginUserHolder.getUserId()));
        }
        requirementInfoRepository.save(requirementInfo);
        return ResultUtil.success();
    }

    @ApiOperation("更新需求状态")
    @PostMapping("/update-status")
    public Result<Void> updateStatus(@RequestBody UpdateRequireStatusReq req) {
        AdminUtils.checkLogin();
        requirementInfoRepository.updateStatus(req.getId(), req.getStatus(), req.getRemark(), LoginUserHolder.getAdminId());
        return ResultUtil.success();
    }

    @ApiOperation("分页查询需求列表")
    @GetMapping("/requirement-page")
    public Result<PageRes<RequirementInfo>> list(@ApiParam("页码，从0页开始") @RequestParam("pageNo") Integer pageNo,
                                                 @ApiParam("每页记录数量") @RequestParam("pageSize") Integer pageSize,
                                                 @ApiParam("处理状态 0-待处理 1-处理中 2-完成 3-取消") @RequestParam(value = "status", required = false) String status,
                                                 @ApiParam("联系人手机号") @RequestParam(value = "contactPhone", required = false) String contactPhone,
                                                 @ApiParam("联系人姓名，支持模糊查询") @RequestParam(value = "contactName", required = false) String contactName,
                                                 @ApiParam("需求标题，支持模糊查询") @RequestParam(value = "title", required = false) String title) {
        AdminUtils.checkLogin();
        // 分页参数
        PageRes<RequirementInfo> pageRes = queryPage(pageNo, pageSize, status, contactPhone, contactName, title, null);
        return ResultUtil.success(pageRes);
    }

    @ApiOperation("商城查询我的需求列表")
    @GetMapping("/my-requirement-list")
    public Result<PageRes<RequirementInfo>> myList(@ApiParam("页码，从0页开始") @RequestParam("pageNo") Integer pageNo,
                                                 @ApiParam("每页记录数量") @RequestParam("pageSize") Integer pageSize) {
        Long userId = LoginUserHolder.getUserId();
        AssertUtil.assertTrue(userId != null && userId > 0, ExceptionEnum.WRONT_TOKEN);
        // 分页参数
        PageRes<RequirementInfo> pageRes = queryPage(pageNo, pageSize, null, null, null, null, userId);
        return ResultUtil.success(pageRes);
    }

    private PageRes<RequirementInfo> queryPage(Integer pageNo, Integer pageSize, String status, String contactPhone, String contactName, String title, Long userId) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "updateTime");
        Pageable pageable = PageRequest.of(pageNo, pageSize, Sort.by(order));
        Specification<RequirementInfo> queryCondition = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = Lists.newArrayList();
            if(StringUtils.isNotEmpty(status)) {
                predicates.add(criteriaBuilder.equal(root.get("status"), status));
            }
            if(StringUtils.isNotEmpty(contactPhone)) {
                predicates.add(criteriaBuilder.equal(root.get("contactPhone"), contactPhone));
            }
            if(StringUtils.isNotEmpty(contactName)) {
                predicates.add(criteriaBuilder.like(root.get("contactName"), "%" + contactName + "%"));
            }
            if(StringUtils.isNotEmpty(title)) {
                predicates.add(criteriaBuilder.like(root.get("title"), "%" + title + "%"));
            }
            if(userId != null) {
                predicates.add(criteriaBuilder.equal(root.get("userId"), userId));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<RequirementInfo> pageList = requirementInfoRepository.findAll(queryCondition, pageable);
        return PageUtils.toPageRes(pageList);
    }


}
